package com.qf.air.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


import com.qf.air.clinet.AirSearchClient;
import com.qf.air.config.RabbitMQConfig;
import com.qf.air.entity.Air;
import com.qf.air.enums.AirEnum;
import com.qf.air.exception.AirEx;
import com.qf.air.mapper.AirMapper;
import com.qf.air.mapper.DistrictMapper;
import com.qf.air.service.AirService;
import com.qf.air.util.R;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.Max;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 维多利加
 * @Date: 2021/3/20 11:02
 */
@Service
public class AirServiceImpl implements AirService {

    @Autowired
    private AirMapper airMapper;
    @Autowired(required = false)
    private DistrictMapper districtMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AirSearchClient airSearchClient;

    @Override
    public PageInfo<Air> findByPageAndDistrictId(Integer page, Integer rows, Integer districtId, String monitoringStation, Date startTime, Date endTime) {
        PageHelper.startPage(page,rows);
        List<Air> all = airMapper.findByDistrictId(districtId,monitoringStation,startTime,endTime);
        //SearchResponse response = elasticAirMapper.indexAir(page, rows, districtId, monitoringStation, startTime, endTime);
        PageInfo<Air> pageInfo = new PageInfo<>(all);
        return pageInfo;
    }

    @Override
    public Map<String,Object> findByPageAndDistrictIdEs(Integer page, Integer rows, Integer districtId, String monitoringStation, Date startTime, Date endTime) {
        String url="http://localhost:9200/search/list?";
        //if (page!=null){
        //    url+="&page="+page.toString();
        //}
        //if (rows!=null){
        //    url+="&rows="+rows.toString();
        //}
        //if (districtId!=null&&districtId!=0){
        //    url+="&districtId="+districtId;
        //}
        //if (!StringUtils.isEmpty(monitoringStation)){
        //    url+="&monitoringStation="+monitoringStation;
        //}
        //if (startTime!=null){
        //    url+="&startTime="+startTime;
        //}
        //if (endTime!=null){
        //    url+="&endTime="+endTime;
        //}
        //MultiValueMap<String,Object> maps =new LinkedMultiValueMap<>();
        Map<String,Object> maps =new HashMap<>();
        maps.put("page",page);
        maps.put("rows",rows);
        maps.put("districtId",districtId);
        maps.put("monitoringStation",monitoringStation);
        maps.put("startTime",startTime);
        maps.put("endTime",endTime);
        //Map<String,Object> result = restTemplate.postForObject(url,maps,Map.class);
        //Map<String,Object> result = restTemplate.getForObject("http://localhost:9200/search/list?maps={maps}",Map.class,maps);
        Map<String,Object> result =airSearchClient.getSearchResponse(maps);
        return result;
    }

    @Override
    public List<Map> districtNameChats() {
        return airSearchClient.getDistrictNameEcharts();
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void save(Air air) throws IOException {
        Integer count = airMapper.save(air);
        Integer districtId = air.getDistrictId();
        String name = districtMapper.findById(districtId).getName();
        air.setDistrictName(name);
        String value = objectMapper.writeValueAsString(air);
        //restTemplate.postForObject("http://localhost:9200/search/add",air, void.class);
        rabbitTemplate.convertAndSend(RabbitMQConfig.AIR_EXCHANGE,"air.save",value);
        if(count !=1){
            //添加失败，记录日志，抛出异常
            System.out.println("添加信息失败！ air="+air);
            throw new AirEx(AirEnum.AIR_ADD_ERROR);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = -1,readOnly = false,rollbackFor = Exception.class,noRollbackFor = ArithmeticException.class)
    public void deleteById(Integer id) throws IOException {
        int i = airMapper.deleteById(id);
        //restTemplate.delete("http://localhost:9200/search/delete/{1}",id);
        rabbitTemplate.convertAndSend(RabbitMQConfig.AIR_EXCHANGE,"air.delete",id);
        if(i!=1){
            System.out.println("删除失败！ id="+id);
            throw new AirEx(AirEnum.AIR_DELETE_ERROR);
        }

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateById(Air air) throws IOException {
        int count = airMapper.updateById(air);
        air.setDistrictName(districtMapper.findById(air.getDistrictId()).getName());
        //restTemplate.put("http://localhost:9200/search/update",air);
        String value = objectMapper.writeValueAsString(air);
        rabbitTemplate.convertAndSend(RabbitMQConfig.AIR_QUEUE,"air.update",value);
        if(count!=1){
            System.out.println("修改失败！ air="+air);
            throw new AirEx(AirEnum.AIR_UPDATE_ERROR);
        }
    }
}
